const express = require('express')
const router = express.Router()
const utility = require('utility')
const db = require('../databases/index')
// 获取
router.get('/userinfo', (req, res) => {
    let sql = `select * from user where id=${req.user.id}`
    db(sql, (err, results) => {
        if (err) {
            throw err
        }
        res.send({
            status: 0,
            message: '获取用户基本信息成功！'
        })
    })
})
// 更新
router.post('/userinfo', (req, res) => {
    let { nickname, email } = req.body
    let sql = `update user set nickname="${nickname}",email="${email}" where id=${req.user.id}`
    db(sql, (err, results) => {
        if (err) {
            throw err
        }
        if (results.affectedRows !== 1) {
            return res.send({
                status: 1,
                message: '更新用户信息失败！'
            })
        }
        res.send({
            status: 0,
            message: "修改用户信息成功！"
        })
    })

})
// 重置密码
router.post('/updatepwd', (req, res) => {
    let { oldPwd, newPwd } = req.body
    // 加密
    oldPwd = utility.md5(oldPwd)
    newPwd = utility.md5(newPwd)
    let sql = `select * from user where   id=${req.user.id} and password="${oldPwd}"`
    db(sql, (err, results) => {
        if (err) {
            throw err
        }
        if (results.length === 0) {
            return res.send({
                status: 1,
                message: '旧密码错误！'
            })
        }
        // 修改
        let sql = `update user set password="${newPwd}" where id=${req.user.id}`
        db(sql, (err, results) => {
            if (err) {
                throw err
            }
            if (results.affectedRows !== 1) {
                return res.send({
                    status: 1,
                    message: '修改密码失败！'
                })
            }
            res.send('更新密码成功！')

        })
    })
})
// 更改用户头像
router.post('/avatar',(req,res)=>{
    let sql= `update user set user_pic="${req.body.avatar}" where id=${req.user.id}`
    db(sql,(err,results)=>{
        if (err) {
            return err
        }
        if (results.affectedRows !== 1) {
            return res.send({
                status:1,
                message:'更新头像失败！'
            })
        }
        res.send({
            status: 0,
            message: "更新头像成功！"
        })
    
    })
})
module.exports = router